/*
 * 版权所有 (c) 2022-2099 TBIT。保留所有权利。
 */

package com.tbit.main.remote.rpc;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tbit.Version;
import com.tbit.common.constant.SystemConstant;
import com.tbit.common.utils.SingUtil;
import com.tbit.common.utils.TraceUtil;
import com.tbit.main.common.JsonResult;
import com.tbit.main.constant.UqbikeManagerConfig;
import com.tbit.main.exception.BaseException;
import com.tbit.main.pojo.Result;
import com.tbit.main.util.LogUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.PostMethod;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理端 Api
 *
 * @author <a href="mailto:li.yao@tbit.com.cn">yao</a>
 * @since 2024/7/9 14:39
 */
@Slf4j
public class UQHttpManager {

    private static HttpClient client = null;

    /**
     * 维持单session
     */
    public static HttpClient getClient() {
        if (client == null) {
            MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
            client = new HttpClient(connectionManager);
            /**设置编码*/
            client.getParams().setContentCharset("UTF-8");
            /**请求超时*/
            client.getHttpConnectionManager().getParams().setConnectionTimeout(3000);
            /**读取超时*/
            client.getHttpConnectionManager().getParams().setSoTimeout(5000);

            // uq http 请求客户端设置请求头参数，添加TraceId
            List<Header> headers = new ArrayList<>();
            headers.add(new org.apache.commons.httpclient.Header(SystemConstant.TRACE_ID, TraceUtil.getTraceIdByLocal()));
            headers.add(new org.apache.commons.httpclient.Header("U-APP-VERSION", Version.VERSION));
            client.getHostConfiguration().getParams().setParameter("http.default-headers", headers);
        }
        return client;
    }

    /**
     * 结束订单
     */
    public static void finish(String userCode, String money, String remark) {
        HttpClient client = getClient();
        PostMethod post = null;

        try {
            post = new PostMethod(UqbikeManagerConfig.managersite + "machineBorrow/finishOrderM.do");
            NameValuePair userCodePair = new NameValuePair("userCode", userCode);
            NameValuePair moneyPair = new NameValuePair("money", money);
            NameValuePair remarkPair = new NameValuePair("remark", remark);
            NameValuePair secretPair = new NameValuePair("secret", UqbikeManagerConfig.secret);
            LogUtil.info("money:" + money + " userCode:" + userCode + " remark:" + remark + " secret:" + UqbikeManagerConfig.secret);
            post.setRequestBody(new NameValuePair[]{userCodePair, moneyPair, remarkPair, secretPair});
            client.executeMethod(post);
            String result = post.getResponseBodyAsString();
            LogUtil.info("强制结束订单=" + result);
            Integer ret = JSON.parseObject(result).getInteger("ret");
            if (ret == 1) {
                LogUtil.info("[" + userCode + "]结束订单成功");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            post.releaseConnection();
        }
    }

    /**
     * 获取运营数据
     */
    public static Map<String, Object> operationalDataToMain(Integer brandId, String accountIds, String startTime, String endTime) {
        try {
            String url = UqbikeManagerConfig.managersite + "/accountDayStat/operationalDataToMain.do";
            // String url = "http://192.168.1.135:60002/accountDayStat/operationalDataToMain.do";
            //String url = "http://192.168.1.22:8083/accountDayStat/operationalDataToMain.do";
            //String url = "http://adminv3test.uqbike.cn/accountDayStat/operationalDataToMain.do";
            Long time = System.currentTimeMillis();
            String sign = SingUtil.createSing(UqbikeManagerConfig.secret + time);
            Map<String, Object> map = new HashMap<>(8);
            map.put("startTime", startTime);
            map.put("endTime", endTime);
            map.put("accountIds", accountIds);
            map.put("brandId", brandId);
            map.put("time", time);
            map.put("sign", sign);
            String result = HttpUtil.get(url, map);
            JSONObject object = JSON.parseObject(result);
            Integer code = object.getInteger("code");
            if (code == HttpStatus.SC_OK) {
                Map<String, Object> mapResult = JSON.parseObject(object.get("data") + "", Map.class);
                return mapResult;
            } else {
                LogUtil.info("管理平台返回失败！" + object);
                return null;
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    public static String rideOrderRefund(Map<String, Object> params) {
        String tempPower = UqbikeManagerConfig.managersite + "/refundOperation/rpc/rideOrderRefund.do";
//        String tempPower = "http://localhost:60002/refundOperation/rpc/rideOrderRefund.do";

        if (log.isInfoEnabled()) {
            log.info("[UQHttpClient][rideOrderRefund][params: {}]", params);
        }

        String resp = UQHttpUtil.sendJsonPut(tempPower, params);

        if (log.isInfoEnabled()) {
            log.info("[UQHttpClient][rideOrderRefund][result: {}]", resp);
        }

        Result<Integer> jsonResult = JSONUtil.toBean(resp, new TypeReference<Result<Integer>>() {
        }, true);

        if (!jsonResult.getCode().equals(HttpStatus.SC_OK)) {
            throw new BaseException(jsonResult.getMsg());
        }

        return JsonResult.succ().getMsg();
    }

    public static void editOrder(Map<String, Object> params) {
        String editOrderUrl = UqbikeManagerConfig.managersite + "/rideLogDetails/rpc/editOrder.do";

        if (log.isInfoEnabled()) {
            log.info("[UQHttpClient][editOrder][params: {}]", params);
        }

        String resp = UQHttpUtil.sendJsonPut(editOrderUrl, params);

        if (log.isInfoEnabled()) {
            log.info("[UQHttpClient][editOrder][result: {}]", resp);
        }

        Result<Integer> jsonResult = JSONUtil.toBean(resp, new TypeReference<Result<Integer>>() {
        }, true);

        if (!jsonResult.getCode().equals(HttpStatus.SC_OK)) {
            throw new BaseException(jsonResult.getMsg());
        }
    }
}
